<?php

namespace Usap\Service\Devices;

use Usap\Service\Service;
use Usap\Model\Common\UtilsModel;

class devices
{


    //API/ADMIN *************公用方法*********************.//

    //类别
    public function getDeviceCategoryConfig()
    {
        return D("Usap/Common/DeviceCategories")->getField('category_id,name');
    }

    //型号
    public function getDeviceTypesConfig()
    {
        return D("Usap/Common/DeviceTypes")->getField('device_type_id,model_identifier');
    }


    /**
     * 添加设备
     * @param array $data 数据集合
     */
    public function addDevice($data)
    {
        $model = D("Usap/Common/Devices");
        if (empty($data['codeserial'])) {
            return array('code' => 'CODESERIAL_NULL', 'msg' => '请输入设备编码');
        }
        if (empty($data['device_type'])) {
            return array('code' => 'DEVICE_TYPE', 'msg' => '请选择设备型号');
        }
        if (empty($data['device_category'])) {
            return array('code' => 'DEVICE_CATEGORY', 'msg' => '请选择设备类型');
        }
        if (empty($data['check_cycle'])) {
            return array('code' => 'CHECK_CYCLE', 'msg' => '请选择巡检周期');
        }
        if (!empty($data['mac_address'])) {//MAC地址唯一
            $exists_no = $model->where("mac_address='" . $data['mac_address'] . "'")->count();
            if ($exists_no) {
                return array('code' => '-1004', 'msg' => '相同MAC地址的设备之前已存在，请重试');
            }
        }
        if (!empty($data['codeserial'])) {//设备编号唯一
            $exists_no = $model->where("codeserial='" . $data['codeserial'] . "'")->count();
            if ($exists_no) {
                return array('code' => '-1005', 'msg' => '相同站点编号的设备之前已存在，请重试');
            }
        }
        $device_id = $model->add($data);
        if ($device_id) {
            $this->buildCheckTask($device_id);
            return array('code' => '0000', 'msg' => '添加成功', 'device_id' => $device_id);
        } else {
            return array('code' => '-1001', 'msg' => '因系统异常，添加失败');
        }
    }

    /**
     * 更新设备
     */
    public function updateDevice($id, $data)
    {
        $model = D("Usap/Common/Devices");
        $res = $model->where(['device_id' => $id])->save($data);
        if ($res) {
//            $this->updateCheckTask($id);//暂缓
            return array('code' => '0000', 'msg' => '更新成功');
        } else {
            return array('code' => '-1001', 'msg' => '因系统异常，添加失败');
        }
    }

    public function updateDeviceBycodeserial($codeserial, $data)
    {
        $model = D("Usap/Common/Devices");
        return $model->where(['codeserial' => $codeserial])->save($data);
    }

    /**
     * 删除设备
     */
    public function deletDevice($id)
    {
        $model = D("Usap/Common/Devices");
        $res = $model->where(['device_id' => $id])->delete();
        if ($res) {
//            $this->deletCheckTask($id); 删除未开始的巡检任务
            return array('code' => '0000', 'msg' => '删除成功');
        } else {
            return array('code' => '-1001', 'msg' => '因系统异常，添加失败');
        }
    }


    /**
     * 根据主键ID更新信息
     * @param int $device_id
     */
    public function updateInfoById($device_id, $update_data_info)
    {
        $model = D("Usap/Common/Devices");
        $device_info = $model->where("device_id='$device_id'")->find();
        if (empty($device_info)) {
            return array('code' => '-1001', 'msg' => '该设备不存在，无法更新');
        }
        if (empty($data['codeserial'])) {
            return array('code' => 'CODESERIAL_NULL', 'msg' => '请输入设备编码');
        }
        if (empty($data['device_type'])) {
            return array('code' => 'DEVICE_TYPE', 'msg' => '请选择设备型号');
        }
        if (empty($data['device_category'])) {
            return array('code' => 'DEVICE_CATEGORY', 'msg' => '请选择设备类型');
        }
        if (empty($data['check_cycle'])) {
            return array('code' => 'CHECK_CYCLE', 'msg' => '请选择巡检周期');
        }
        if (!empty($data['mac_address']) && ($data['mac_address'] != $device_info['mac_address'])) {//MAC地址唯一
            $exists_no = D("Usap/Authpuppy/Nodes")->where("mac_address='" . $data['mac_address'] . "'")->count();
            if ($exists_no) {
                return array('code' => '-1004', 'msg' => '相同MAC地址的设备之前已存在，请重试');
            }
        }
        if (!empty($data['codeserial']) && ($data['codeserial'] != $device_info['codeserial'])) {//站点编号唯一

            $exists_no = D("Usap/Authpuppy/Nodes")->where("codeserial='" . $data['codeserial'] . "'")->count();
            if ($exists_no) {

                return array('code' => '-1005', 'msg' => '设备编号已存在，请重试');
            }
        }
        $result = $model->where("device_id='$device_id'")->save($data);
        if ($result) {
            return array('code' => '0000', 'msg' => '操作成功');
        }
        return array('code' => 'opt_fail', 'msg' => '数据未做任何更新');
    }

    /**
     * 根据主键ID获取信息
     * @param int $device_id
     * @return array();
     */
    public function getInfoByDeviceId($device_id)
    {
        $this->crontabMonitor();
        $model = D("Usap/Common/Devices");
        $device_info = $model->where("device_id='$device_id'")->find();
        if (empty($device_info)) {
            return array();
        }
        return $device_info;
    }

    /**
     * 根据设备编码获取信息列表
     * @param string $codeserial
     */
    public function getInfoByCodeserial($codeserial)
    {
        $this->crontabMonitor();
        $model = D("Usap/Common/Devices");
        $device_info = $model->where("codeserial='$codeserial'")->find();
        if (empty($device_info)) {
            return array();
        }
        return $device_info;
    }


    /**
     * 通过信息获取信息列表
     * @param array $where
     * @param number $page
     * @param number $rows
     * @param string $desc
     * @param string $sort
     */
    public function getDeviceList($where, $page = 1, $rows = '', $sort = 'device_id', $desc = 'asc')
    {
        $this->crontabMonitor();
        $model = D("Usap/Common/Devices");
        $list = [];
        $order = $sort . ' ' . $desc;
        $count = $model->where($where)->count();
        if ($count > 0) {
            if ($rows) {
                $list = $model->where($where)->page($page, $rows)->order($order)->select();
            } else {
                $list = $model->where($where)->select();
            }
        }
        $result = [
            'count' => $count ? $count : 0,
            'list' => $list,
        ];
        return $result;
    }


    /**
     * 获取设备信息
     * by  @param string $condition
     */
    public function getDeviceByCondition($condition)
    {
        $model = D("Usap/Common/Devices");
        return $model->where($condition)->select();

    }


    public function getDeviceListByFor($where)
    {
        $this->crontabMonitor();
        $model = D("Usap/Common/Devices");
        $list = $model->field('a.*,b.district')->alias('a')->join('left join places as b on a.place_id = b.place_id')->where($where)->select();
        return $list;
    }

    public function getDeviceInfoByCondition($where, $files = '*')
    {
        $this->crontabMonitor();
        $model = D("Usap/Common/Devices");
        return $model->field($files)->where($where)->select();
    }

    /**
     * 生成设备初次巡检任务
     * @param int $device_id
     */
    public function buildCheckTask($device_id)
    {
        $cycleconfi = Service::instance()->loadConfig('Common', 'device', 'getCheckCycle');
        $device_info = $this->getInfoByDeviceId($device_id);
        $begin = $cycleconfi[$device_info['check_cycle']] - 5;//开始间隔
        $end = $cycleconfi[$device_info['check_cycle']];//到周期截止
        $begin_time = date('Y-m-d', strtotime('+' . $begin . 'day'));//开始时间为周期的前一天
        $end_time = date('Y-m-d', strtotime('+' . $end . 'day'));
        $taskName = $device_info['device_address'];
        $data = [
            'device_id' => $device_id,
            'code' => date('YmdHis'),
            'codeserial' => $device_info['codeserial'],
            'taskName' => $taskName,
            'cycle' => $cycleconfi[$device_info['check_cycle']],
            'begin_time' => $begin_time,
            'end_time' => $end_time,
        ];
        $model = D("Usap/Common/CheckTask");
        $model->add($data);
    }


    public function getReportListByCondition($where)
    {
        return D('Usap/Common/ReportLog')->where($where)->select();
    }

    /**
     * 更新设备状态
     */
    public function crontabMonitor()
    {
        $date = date('Y-m-d H:i:s', strtotime('-1 day'));//前一天
        $data = [
            'is_online' => 0
        ];
        $where = " last_report_time <'$date'";
        $model = D("Usap/Common/Devices");
        $model->where($where)->save($data);
    }

}
